//
//  SelPayMethodViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/8/7.
//  Copyright © 2019 王洋. All rights reserved.
//

#import <WXApi.h>

#import "TTAlipayAuthManager.h"
#import "SelPayMethodViewController.h"
#import "OrderCenterViewController.h"

@interface SelPayMethodViewController ()

//需付金额
@property (weak, nonatomic) IBOutlet UILabel *totalPayMoneyLab;

//支付宝支付
@property (weak, nonatomic) IBOutlet UIView *alipayActionView;

//微信支付
@property (weak, nonatomic) IBOutlet UIView *weChatPayActionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *weChatHeight;

//余额支付
@property (weak, nonatomic) IBOutlet UIView *balancePayActionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *balanceHeight;

@property (copy, nonatomic) NSString *outTradeNo;

//余额LAB
@property (weak, nonatomic) IBOutlet UILabel *balanceLab;



@end

@implementation SelPayMethodViewController

-(void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"payResultNotification" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initView];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(payResultCallBack:) name:@"payResultNotification" object:nil];
}

-(void)payResultCallBack:(NSNotification *)Noti {
    
    BOOL isPaySuccess = [[Noti.userInfo objectForKey:@"resultStatus"] boolValue];
    NSString *resultMsg = [Noti.userInfo objectForKey:@"memo"];
    NSString *payType = [Noti.userInfo objectForKey:@"payType"];

    [self loadPayResultViewWith:isPaySuccess Msg:resultMsg AndType:payType];
}

-(void)loadPayResultViewWith:(BOOL)payResult Msg:(NSString *)msg AndType:(NSString *)payType {
    
        if ([payType isEqualToString:@"alipay"]) {
            [self request_NotificationServerAlipay];
        }
        
        if ([payType isEqualToString:@"wechat"]) {
            [self request_NotificationServerWechat];
        }

        if (payResult) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:@"orderRefreshNoti" object:nil userInfo:nil];
            });
            
            switch (self.payForType) {
                case PP_PayType_ForRecharge: {
                    [self popForRecharge];
                } break;
                    
                case PP_PayType_ForOrder: {
                    [self popForOrder];
                } break;
                    
                default:
                    break;
            }
            
        } else {
            
            [self alert:msg];

        }
}

- (void)popForRecharge {
    
    [self.navigationController popToRootViewControllerAnimated:NO];
    [SVProgressHUD showSuccessWithStatus:@"充值成功"];
    [SVProgressHUD dismissWithDelay:1];
}

- (void)popForOrder {
    WEAKSELF
    [self alert:@"支付成功" leftTitle:@"回订单" Action:^(UIAlertAction * _Nonnull action) {
        
        for (UIViewController *vc in self.navigationController.viewControllers) {
            if ([vc isKindOfClass:[OrderCenterViewController class]]) {
                [weakSelf.navigationController popToViewController:vc animated:YES];
            }
        }
        
    } rightTitle:@"回首页" Action:^(UIAlertAction * _Nonnull action) {
        
        [weakSelf.navigationController popToRootViewControllerAnimated:NO];
        [PPTabBarController setCurrentIndex:PPTabbarIndexTypeHome];
    }];
}

- (void)initView {
    
    self.title = @"选择支付方式";
    self.totalPayMoneyLab.text = [NSString stringWithFormat:@"¥ %@",self.money];
    
    self.alipayActionView.userInteractionEnabled = YES;
    self.weChatPayActionView.userInteractionEnabled = YES;
    self.balancePayActionView.userInteractionEnabled = YES;
    
    if ([WXApi isWXAppInstalled]) {

    } else {

        self.weChatHeight.constant = CGFLOAT_MIN;
    }
    
    
    //如果是充值，则不显示余额支付
    switch (self.payForType) {
        case PP_PayType_ForRecharge:{
            
            self.balanceHeight.constant = CGFLOAT_MIN;
            
        } break;
            
        case PP_PayType_ForOrder:{
            
            [self request_PayMoneyAndBalance];
            
        } break;
            
        default:
            break;
    }
    
    WEAKSELF
    [self.alipayActionView addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {

        [weakSelf request_AlipayParam];
    }];
    
    [self.weChatPayActionView addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {

        [weakSelf request_WXPayParam];
    }];
    
    [self.balancePayActionView addGestureTapEventHandle:^(id  _Nonnull sender, UITapGestureRecognizer * _Nonnull gestureRecognizer) {

        [weakSelf request_BalanceParam];
    }];
    
}

//调取微信支付
- (void)callWechatPayWithInfo:(NSDictionary *)orderInfo {

    PayReq *request = [[PayReq alloc] init];
    request.openID = [orderInfo objectForKey:@"appid"];
    request.partnerId =     [orderInfo objectForKey:@"partnerid"];
    request.prepayId =      [orderInfo objectForKey:@"prepayid"];
    request.package =       [orderInfo objectForKey:@"packageValue"];
    request.nonceStr =      [orderInfo objectForKey:@"noncestr"];
    NSString *stamp =       [orderInfo objectForKey:@"timestamp"];
    request.timeStamp =     stamp.intValue;
    request.sign =          [orderInfo objectForKey:@"sign"];
    [WXApi sendReq:request];
}

- (void)request_PayMoneyAndBalance {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderId forKey:@"id"];

    WEAKSELF
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_ORDER_PRICE];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {

                    double remainder = [[resultDic valueForKey:@"remainder"] doubleValue];
                    double orderPrice = [[resultDic valueForKey:@"orderPrice"] doubleValue];

                    weakSelf.balanceLab.text = [NSString stringWithFormat:@"余额支付(可用：¥%@)",[Utilities changeDoubleToString:remainder]];
                    weakSelf.money = [NSString stringWithFormat:@"%@",[Utilities changeDoubleToString:orderPrice]];
                    weakSelf.totalPayMoneyLab.text = [NSString stringWithFormat:@"¥ %@",weakSelf.money];
                }
                
            } else {
                
                [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                [SVProgressHUD dismissWithDelay:1];
            }
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)request_AlipayParam {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderId forKey:@"orderId"];
    [dic setValue:@(self.payForType) forKey:@"payType"];
    
    if (self.payForType == PP_PayType_ForRecharge) {
        [dic setValue:self.money forKey:@"amount"];
    }

    WEAKSELF
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_PAY_ALIPAY];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    NSString *orderStr = [resultDic valueForKey:@"orderString"];
                    [[TTAlipayAuthManager manager] payWithOrderString:orderStr];
                    weakSelf.outTradeNo = [resultDic valueForKey:@"outTradeNo"];
                }
                
            } else {
                
                [self alert:[data valueForKey:@"msg"]];

            }
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
    
}

- (void)request_WXPayParam {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderId forKey:@"orderId"];
    [dic setValue:@(self.payForType) forKey:@"payType"];

    if (self.payForType == PP_PayType_ForRecharge) {
        [dic setValue:self.money forKey:@"amount"];
    }
    
    WEAKSELF
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_PAY_WXPAY];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                NSDictionary *resultDic = [data valueForKey:@"data"];
                if ([resultDic isKindOfClass:[NSDictionary class]]) {
                    
                    [weakSelf callWechatPayWithInfo:resultDic];
                    weakSelf.outTradeNo = [resultDic valueForKey:@"outTradeNo"];
                }
                
            } else {
                
                [self alert:[data valueForKey:@"msg"]];

            }
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}

- (void)request_BalanceParam {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.orderId forKey:@"orderId"];
    [dic setValue:@(self.payForType) forKey:@"payType"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_PAY_BALANCEPAY];

    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
                NSMutableDictionary *payDic = @{}.mutableCopy;
                [payDic setValue:@"支付成功" forKey:@"memo"];
                [payDic setValue:@"支付成功" forKey:@"msg"];
                [payDic setValue:@"balance" forKey:@"payType"];
                [payDic setValue:@"1" forKey:@"resultStatus"];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"payResultNotification" object:nil userInfo:payDic];
                
            } else {
                
                [self alert:[data valueForKey:@"msg"]];
            }
            
        } else {
            
        }
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
}


- (void)request_NotificationServerAlipay {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.outTradeNo forKey:@"outTradeNo"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_NOTIFICATION_SERVER_ALIPAY];
    
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {

        //请求后再发通知刷新详情和列表
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
            } else {
                [weakSelf request_NotificationServerAlipay];
            }
            
            
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
    
}

- (void)request_NotificationServerWechat {
    
    NSMutableDictionary *dic = @{}.mutableCopy;
    [dic setValue:self.outTradeNo forKey:@"outTradeNo"];

    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_NOTIFICATION_SERVER_WECHAT];
    WEAKSELF
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        //请求后再发通知刷新详情和列表
        
        if ([data isKindOfClass:[NSDictionary class]]) {
            
            NSString * code = [data valueForKey:@"code"];
            if ([code isEqualToString:@"200"]) {
                
            } else {
                [weakSelf request_NotificationServerWechat];
            }
            
            
        }

    } FailedBlock:^(NSError * _Nonnull error) {
        
    }];
    
}



@end
